package pl.kemot.impl.customer.all;

import java.util.List;

import pl.kemot.customer.all.IPresenterCustomerAll;
import pl.kemot.customer.all.IViewCustomerAll;
import pl.kemot.model.CustomerDTO;

import com.vaadin.data.Item;
import com.vaadin.ui.Component;
import com.vaadin.ui.Table;

@SuppressWarnings("serial")
public class ViewCustomerAllImpl extends Table implements IViewCustomerAll {
	private static final String ID = "Id";
	private static final String AGE = "Wiek";
	private static final String LAST_NAME = "Nazwisko";
	private static final String FIRST_NAME = "Imię";
	private IPresenterCustomerAll presenterCustomerAll;

	public ViewCustomerAllImpl(String caption, IPresenterCustomerAll presenterCustomerAll) {
		super(caption);
		this.presenterCustomerAll = presenterCustomerAll;
		this.presenterCustomerAll.setViewCustomerAll(this);

		addContainerProperty(ID, Long.class, null);
		addContainerProperty(FIRST_NAME, String.class, null);
		addContainerProperty(LAST_NAME, String.class, null);
		addContainerProperty(AGE, Integer.class, null);

		loadData();
	}

	@Override
	public CustomerDTO getCustomerById(Long id) {
		Item item = getItem(id);
		CustomerDTO customerDTO = new CustomerDTO();
		customerDTO.setId((Long) item.getItemProperty(ID).getValue());
		customerDTO.setFirstName(item.getItemProperty(FIRST_NAME).getValue().toString());
		customerDTO.setLastName(item.getItemProperty(LAST_NAME).getValue().toString());
		customerDTO.setAge((Integer) item.getItemProperty(AGE).getValue());
		return customerDTO;
	}

	@Override
	public void setCustomer(List<CustomerDTO> list) {
		for (CustomerDTO customerDTO : list) {
			addCustomer(customerDTO);
		}
	}

	@Override
	public void addOrUpdateCustomer(CustomerDTO customerDTO) {
		Item updatedItem = getItem(customerDTO.getId());
		if (updatedItem == null) {
			addCustomer(customerDTO);
		} else {
			updatedItem.getItemProperty(FIRST_NAME).setValue(customerDTO.getFirstName());
			updatedItem.getItemProperty(LAST_NAME).setValue(customerDTO.getLastName());
			updatedItem.getItemProperty(AGE).setValue(customerDTO.getAge());
		}
	}

	@Override
	public Component getComponent() {
		return this;
	}

	public void loadData() {
		presenterCustomerAll.perform(null);
	}

	private void addCustomer(CustomerDTO customerDTO) {
		addItem(new Object[] { customerDTO.getId(), //
				customerDTO.getFirstName(), //
				customerDTO.getLastName(), //
				customerDTO.getAge() }, //
				customerDTO.getId());
	}
}
